package me.zhengjie.modules.quartz.task;

import com.qiaofang.applet.common.util.RedisKeyUtil;
import com.qiaofang.applet.service.other.domain.Corporation;
import com.qiaofang.applet.service.other.service.CorporationService;
import com.qiaofang.applet.service.other.service.YxImMessageService;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class MessageListTask {

    //集团
    @Autowired
    private CorporationService corporationService;
    //城市公司
    @Autowired
    private YxImMessageService yxImMessageService;

    @Autowired
    private RedisUtils redisUtils;


    public void run() {
        String taskKey = RedisKeyUtil.getTaskKey(this.getClass().getSimpleName());
        if (redisUtils.hasKey(taskKey)){
            return;
        }
        redisUtils.set(taskKey, "", 2, TimeUnit.HOURS);

        Corporation corporation = new Corporation();
        corporation.setDeleted(Boolean.FALSE);
        Iterable<Corporation> list = corporationService.findAll(Example.of(corporation));
        list.forEach(item -> {
            String corporationCode = item.getCorporationCode();
            log.info("开始处理集团:{}的微聊数据，开始时间:{}", item.getCorporationName(), new Date());
            try {
                yxImMessageService.opYxImMessage(corporationCode);
            } catch (Exception e) {
                redisUtils.del(taskKey);
                log.error("处理集团:{}的微聊数据出错:{}", item.getCorporationName(), e);
            }
            log.info("完成处理集团:{}的微聊数据，完成时间:{}", item.getCorporationName(), new Date());
        });

        redisUtils.del(taskKey);
    }
}
